﻿/*
Audica Uploader - application for convenient uploading to various file hostings
Copyright (C) 2011-2012 Makarov Andrey (Winand)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <QLocalSocket>

#include "singleapplication.h"

SingleApplication::SingleApplication(int &argc, char *argv[], const QString uniqueKey) :
    QApplication(argc, argv), _uniqueKey(uniqueKey)
{
    sharedMemory.setKey(_uniqueKey);
    if (sharedMemory.attach())
        _isRunning = true;
    else {
        _isRunning = false;
        // create shared memory.
        if (!sharedMemory.create(1)) {
            qDebug("Unable to create single instance.");
            return;
        }
        // create local server and listen to incomming messages from other instances.
        localServer = new QLocalServer(this);
        connect(localServer, SIGNAL(newConnection()), this, SLOT(receiveMessage()));
        localServer->listen(_uniqueKey);
    }
}

// public slots.

void SingleApplication::receiveMessage() {
    QLocalSocket *localSocket = localServer->nextPendingConnection();
    if (!localSocket->waitForReadyRead(timeout)) {
        qDebug(localSocket->errorString().toLatin1());
        return;
    }
    int msgtype;
    QList<QString> message;
    QDataStream stream(localSocket);
    stream >> msgtype;
    if(msgtype == QList_QString) { //check datatype
        stream >> message;
        if(stream.status() == QDataStream::Ok)
        /*QByteArray byteArray  = localSocket->readAll();
        QString message = QString::fromUtf8(byteArray.constData());*/
        emit messageAvailable(message);
    } else qDebug() << "SingleApplication::receiveMessage()" << "unknown datatype received";
    localSocket->disconnectFromServer();
}

// public functions.

bool SingleApplication::isRunning() {
    return _isRunning;
}

bool SingleApplication::sendMessage(const QList<QString> message) {
    if (!_isRunning)
        return false;
    QLocalSocket localSocket(this);
    localSocket.connectToServer(_uniqueKey, QIODevice::WriteOnly);
    if (!localSocket.waitForConnected(timeout)) {
        qDebug("Couldn't connect to server: " + localSocket.errorString().toLatin1());
        return false;
    }
    QDataStream stream(&localSocket);
    stream << QList_QString;
    stream << message;
    /*localSocket.write(message.toUtf8());*/
    if (!localSocket.waitForBytesWritten(timeout)) {
        qDebug("Couldn't send message to server: " + localSocket.errorString().toLatin1());
        return false;
    }
    localSocket.disconnectFromServer();
    return true;
}
